﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;
using SELinks;

/*
Developed By: Sujeet Kumar
Developed On: 6th July 2011
Description: This code displays the Site Links contents
*/

namespace SELinks.SE_Links
{
    public partial class SE_LinksUserControl : UserControl
    {
        SharepointManager objSharepointManager = new SharepointManager();
        
       protected void Page_Load(object sender, EventArgs e)
        {
                if (!Page.IsPostBack)
                {
                    // Create Link list
                    CreateMyLinkList();

                    // Create Add and manage navigate Url
                    GetAddAndManageLink();
                   

                    //Fill Treeview with links
                    PopulateTreeViewControlLink();
                }
        }

       
        // Create My Link list
        private void CreateMyLinkList()
        {
            try
            {
                Boolean chkListExists;
                SPWeb myWeb = SharepointManager.GetCurrentWeb();

                chkListExists = SharepointManager.ListExists(myWeb, "Site Links");

                if (!chkListExists)
                {
                    SharepointManager.CreateNewList("Site Links", "Site Links List", SPListTemplateType.GenericList);
                }

                using (SPSite sitecol = myWeb.Site)
                {
                    using (SPWeb myDifferentWeb = sitecol.OpenWeb())
                    {
                        myDifferentWeb.AllowUnsafeUpdates = true;
                        SPList list = myDifferentWeb.Lists["Site Links"];
                        list.OnQuickLaunch = true;
                        Boolean chkFieldExists = list.Fields.ContainsField("Group");
                        if (list != null && !chkFieldExists)
                        {
                            SPField titleField = list.Fields.GetField("Title");                            
                            string newField = string.Concat("<Field Type='Choice' DisplayName='Group' Name='Group' Format='Dropdown' Required='TRUE' FillInChoice='TRUE'><CHOICES>", "<CHOICE>General Resources</CHOICE><CHOICE>Research Services</CHOICE></CHOICES>", "<Default>General Resources</Default>", "</Field>");
                            list.Fields.AddFieldAsXml(newField, true, SPAddFieldOptions.Default);                           
                            list.Fields.Add("URL", SPFieldType.URL, true);                            
                             list.Update();
                            SPView view = list.DefaultView;                          
                            view.ViewFields.Add("Title");
                            view.ViewFields.Add("URL");                           
                            view.ViewFields.Add("Created By");
                            view.ViewFields.Add("Created");
                         //   view.Query =
                         //"<Where>" +
                         //"<Eq><FieldRef Name=\"Author\"/><Value Type=\"Integer\"><UserID Type=\"Integer\" /> </Value></Eq>" +
                         //"</Where>";
                            if (view.ViewFields.Exists("LinkTitle"))
                            {
                                view.ViewFields.Delete("LinkTitle");
                            }
                            view.Update();
                        }
                    }
                }

            }
            catch (Exception)
            {
            }
        }

        //Fetch and Populate all the Links 
        private DataTable Getlinks()
        {
            DataTable dtMyLinks = new DataTable();
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Site Links"];
                        SPListItemCollection itemColl;
                        SPQuery query = new SPQuery();
                        query.Query =
                          "<OrderBy><FieldRef Name=\"Created\" Ascending=\"FALSE\"></FieldRef></OrderBy>";

                        itemColl = list.GetItems(query);                        

                        dtMyLinks.Columns.Add("Id", typeof(String));
                        dtMyLinks.Columns.Add("Group", typeof(String));
                        dtMyLinks.Columns.Add("Title", typeof(String));
                        dtMyLinks.Columns.Add("LinkUrl", typeof(String));
                        dtMyLinks.Columns.Add("LinkUrlDesc", typeof(String));

                        if (itemColl.Count > 0)
                        {
                            for (int icount = 0; icount < itemColl.Count; icount++)
                            {
                                SPListItem listItem = itemColl[icount];
                                DataRow drMyLink = dtMyLinks.NewRow();

                                drMyLink["Id"] = listItem["ID"].ToString();
                                drMyLink["Title"] = listItem["Title"].ToString();
                                drMyLink["Group"] = listItem["Group"].ToString();

                                SPFieldUrlValue value = new SPFieldUrlValue(listItem["URL"].ToString());

                                drMyLink["LinkUrl"] = value.Url;

                                if (value.Description == "")
                                    drMyLink["LinkUrlDesc"] = value.Url;
                                else
                                    drMyLink["LinkUrlDesc"] = value.Description;

                                dtMyLinks.Rows.Add(drMyLink);
                            }
                        }
                        else
                        {
                            
                            lblMessage.Text = "You have not created any links.";
                        }
                    }
                }
            }
            catch
            {
            }

            return dtMyLinks;
        }

        // This method is used to populate the TreeView Control with Links 
        private void PopulateTreeViewControlLink()
        {
            DataTable dtLinks = new DataTable();            
            dtLinks = Getlinks();
            if (dtLinks.Rows.Count > 0)
            {
                try
                {
                    dtLinks.PrimaryKey = new DataColumn[] { dtLinks.Columns["Id"] };
                    ArrayList arrayGroup = new ArrayList();
                    ArrayList arrayGroupUnique = new ArrayList();
                    foreach (DataRow dr in dtLinks.Rows)
                    {
                        string parentGroup = string.Empty;
                        parentGroup = dr.ItemArray[1].ToString();
                        arrayGroup.Add(parentGroup);
                    }

                    foreach (string group in arrayGroup)
                    {
                        if (!arrayGroupUnique.Contains(group))
                        {
                            arrayGroupUnique.Add(group);
                        }
                    }

                    foreach (string group in arrayGroupUnique)
                    {
                        TreeNode parentNode = new TreeNode(group);
                        parentNode.SelectAction = TreeNodeSelectAction.None;
                        tvMyLinks.Nodes.Add(parentNode);
                        DataTable dtchild = new DataTable();   
                        ArrayList arrChild = new ArrayList();
                        foreach (DataRow dra in dtLinks.Rows)
                        {
                            if (dra["Group"].ToString().ToLower() == group.ToLower())
                            {
                                string uniqueTitle = dra["Title"].ToString().ToLower() + dra["LinkUrl"].ToString().ToLower();
                                if (!arrChild.Contains(uniqueTitle))
                                {
                                    TreeNode childNode = new TreeNode(dra["Title"].ToString());
                                    childNode.SelectAction = TreeNodeSelectAction.Select;
                                    childNode.NavigateUrl = dra["LinkUrl"].ToString();
                                    childNode.Target = "_blank";
                                    parentNode.ChildNodes.Add(childNode);
                                }
                                arrChild.Add(uniqueTitle);
                            }
                            
                        }
                      
                    }

                }
                catch
                {

                }
            }
            else
            {
                
            }

        }

        // Create Add and manage navigate Url
        protected void GetAddAndManageLink()
        {
            string addLinkUrl, manageLinkUrl = string.Empty;
            SPSite Site = SPContext.Current.Site;
            SPWeb web = Site.OpenWeb();
            SPList List = web.Lists["Site Links"];
            addLinkUrl = SPContext.Current.Site.Url + "/" + "Lists" + "/" + "Site Links/NewForm.aspx";
            manageLinkUrl = SPContext.Current.Site.Url + "/" + "Lists" + "/" + "Site Links/AllItems.aspx";
            web.Dispose();
            hlkAddLink.NavigateUrl = addLinkUrl;
            hlkManageLink.NavigateUrl = manageLinkUrl;
        }



       
    }
}

